package com.ddwl.user.service;

import com.ddwl.common.util.UUIDGenerator;
import com.ddwl.schema.bo.user.ChildrenBo;
import com.ddwl.schema.bo.user.ChildrenPicBo;
import com.ddwl.schema.vo.user.ChildrenPicVo;
import com.ddwl.schema.vo.user.ChildrenVo;
import com.ddwl.user.dao.mapper.ChildrenMapper;
import com.ddwl.user.dao.mapper.ChildrenPicMapper;
import com.ddwl.user.dao.model.Children;
import com.ddwl.user.dao.model.ChildrenPic;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author Fu Zhaohui
 * @date 2017/2/26
 */
@Service
public class ChildrenService {

    @Autowired
    private ChildrenMapper childrenMapper;
    @Autowired
    private ChildrenPicMapper childrenPicMapper;


    @Transactional(rollbackFor = Throwable.class)
    public void create(ChildrenBo bo) {
        Children entity = new Children();
        BeanUtils.copyProperties(bo, entity);
        entity.setId(UUIDGenerator.getShortUUID());
        childrenMapper.insert(entity);
        List<ChildrenPicBo> picBos = bo.getPics();
        if (picBos != null && !picBos.isEmpty()) {
            List<ChildrenPic> pics = picBos.stream().map(picBo -> {
                ChildrenPic pic = new ChildrenPic();
                BeanUtils.copyProperties(picBo, pic);
                pic.setChildrenId(entity.getId());
                pic.setId(UUIDGenerator.getShortUUID());
                return pic;
            }).collect(Collectors.toList());
            childrenPicMapper.batchInsert(pics);
        }
    }

    public List<ChildrenVo> getByUser(String userId) {
        List<Children> entities = childrenMapper.findByUserId(userId);
        if (entities.isEmpty()) {
            return new ArrayList<>(0);
        }
        return entities.stream().map(entity -> {
            ChildrenVo vo = new ChildrenVo();
            BeanUtils.copyProperties(entity, vo);
            List<ChildrenPic> pics = Optional.ofNullable(entity.getPics()).orElse(new ArrayList<>(0));
            List<ChildrenPicVo> picVos = pics.stream().map(pic -> {
                ChildrenPicVo picVo = new ChildrenPicVo();
                BeanUtils.copyProperties(pic, picVo);
                return picVo;
            }).collect(Collectors.toList());
            vo.setPics(picVos);
            return vo;
        }).collect(Collectors.toList());
    }
}
